﻿Imports System.IO
Imports System.Data.OleDb

Module Mdl_Main

    Public UzakServis As New SmartOfficeService.Service
    Public Sql_Server As String
    Public Database_Name As String
    Public Cnn_String As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Persist Security Info=True;Jet OLEDB:Database Password=s1h2i3e4l5d6", Application.StartupPath & "\VT\MikroMagaza.mdb")
    Public Merkez_Depo_Kodu As String = ""
    Public Firma_Kod As String
    Public Donem_Kod As String
    Private DovizListe As New System.Collections.Generic.Dictionary(Of Integer, Decimal)
    Public Depo_Kod As String
    Public Servis_Url As String
    Public Yazici_Yolu As String
    Public Terazi_Yolu As String
    Public Kasa_yolu As String
    Public Etiket_Miktari As Integer
    Public Kasa_Tipi As KasaTipi
    Public Pasif_Stok_Aktarilsin As Boolean = False
    Public Opa_Yol As String = "c:\genius\office\geniusopa.exe"
    Public Kasa_Kod As String = ""
    Public Uzak_kasa_yol As String = ""
    Public SatisDosyaAdi As String = ""
    Public SatisDepoKod As String = ""
    Public HalkDepoKod As String = ""
    Public HalkGunu As String
    Public ProgramTipi As ProgramTipleri
    Public CalismaSekli As CalismaTipi = CalismaTipi.Servis
    Public ImportsFile As String = ""
    Public TeraziTipi As TeraziTip = TeraziTip.ishida
    Public LookAndFeel As New DevExpress.LookAndFeel.DefaultLookAndFeel
    Public otoSendTime As String
    Public KdvSiralamasi As String
    Public fiyatGruplari As String


    Public Enum TeraziTip
        ishida = 0
        cas = 1
        DigiSM300 = 2
        CASLP500 = 3
        casLp1 = 4
    End Enum
    Public Enum CalismaTipi
        Servis = 0
        Dosya = 1
        'GeniusOpen = 3
    End Enum
    Public Enum KasaTipi
        NCR = 0
        Genius = 1
        Inter = 2
        Wincor = 3
    End Enum

    Public Enum Gunler
        Pazartesi = 1
        Salı = 2
        Çarşamba = 3
        Perşembe = 4
        Cuma = 5
        Cumartesi = 6
        Pazar = 7
    End Enum

    Public Enum ProgramTipleri
        MikroV10 = 0
        MikroV12 = 1
        MikroV14 = 2
        MikroV15 = 3
    End Enum

    Public Function BugunAdi() As String
        Select Case Now.DayOfWeek
            Case DayOfWeek.Friday
                Return "Cuma"
            Case DayOfWeek.Monday
                Return "Pazartesi"
            Case DayOfWeek.Saturday
                Return "Cumartesi"
            Case DayOfWeek.Sunday
                Return "Pazar"
            Case DayOfWeek.Thursday
                Return "Perşembe"
            Case DayOfWeek.Tuesday
                Return "Salı"
            Case DayOfWeek.Wednesday
                Return "Çarşamba"
        End Select
        Return ""
    End Function

    Public Function BugunNo(ByVal gunAdi As String) As String
        Select Case gunAdi
            Case "Cuma"
                Return 5
            Case "Pazartesi"
                Return 1
            Case "Cumartesi"
                Return 6
            Case "Pazar"
                Return 7
            Case "Perşembe"
                Return 4
            Case "Salı"
                Return 2
            Case "Çarşamba"
                Return 3
        End Select
        Return 1
    End Function


    Public Function GunKontrol() As Integer
        Dim bugun As String = BugunAdi()
        Dim depoNo As Integer = Depo_Kod
        Dim gun() As String = HalkGunu.Split(",")
        Dim idx As Integer = -1
        For i As Integer = 0 To gun.Length - 1
            If gun(i).Trim().ToLower() = bugun.Trim().ToLower() Then
                idx = i
                Exit For
            End If
        Next

        If idx > -1 Then
            Dim dp() As String = HalkDepoKod.Split(",")
            depoNo = dp(idx).Trim()
        End If
        Return depoNo
    End Function

    Public Enum ProgramAyarlari
        Sql_Server
        Database_Name
        Local_Database_Name
        Imported_Database_Name
        Depo_Kod
        Servis_Url
        Yazici_Yolu
        Terazi_Yolu
        Kasa_yolu
        Etiket_Miktari
        Kasa_Tipi
        Pasif_Stok_Aktarilsin
        Opa_Yol
        Kasa_Kod
        Uzak_kasa_yol
        SatisDosyaAdi
        SatisDepoKod
        HalkDepoKod
        HalkGunu
        ProgramTipi
        CalismaSekli
        ImportsFile
        TeraziTipi
        otosendTime
        KdvSiralamasi
        fiyatGruplari
    End Enum

    Public Sub Ayar_Oku()

        If System.IO.File.Exists(Application.StartupPath & "\settings.bin") Then
            Dim obj As MikroMagazaObject.SettingsObject = MikroMagazaObject.Settings.Get
            Sql_Server = obj.Sql_Server
            Database_Name = obj.Database_Name
            Merkez_Depo_Kodu = obj.Merkez_Depo_Kodu
            Firma_Kod = obj.Firma_Kod
            Donem_Kod = obj.Donem_Kod
            Depo_Kod = obj.Depo_Kod
            Servis_Url = obj.Servis_Url
            Yazici_Yolu = obj.Yazici_Yolu
            Terazi_Yolu = obj.Terazi_Yolu
            Kasa_yolu = obj.Kasa_yolu
            Etiket_Miktari = obj.Etiket_Miktari
            Kasa_Tipi = obj.Kasa_Tipi
            Pasif_Stok_Aktarilsin = obj.Pasif_Stok_Aktarilsin
            Opa_Yol = obj.Opa_Yol
            Kasa_Kod = obj.Kasa_Kod
            Uzak_kasa_yol = obj.Uzak_kasa_yol
            SatisDosyaAdi = obj.SatisDosyaAdi
            SatisDepoKod = obj.SatisDepoKod
            HalkDepoKod = obj.HalkDepoKod
            HalkGunu = obj.HalkGunu
            ProgramTipi = obj.ProgramTipi
            CalismaSekli = obj.CalismaSekli
            ImportsFile = obj.ImportsFile
            TeraziTipi = obj.TeraziTipi
            otoSendTime = obj.otoSendTime
            KdvSiralamasi = obj.KdvSiralamasi
            fiyatGruplari = obj.fiyatGruplari
        Else
            If System.IO.File.Exists(Application.StartupPath & "\Ayarlar.xml") Then
                Dim AyarDs As New DataSet
                AyarDs.ReadXml(Application.StartupPath & "\Ayarlar.xml")
                System.IO.File.Delete(Application.StartupPath & "\Ayarlar.xml")

                If AyarDs.Tables(0).Rows.Count > 0 Then

                    Sql_Server = AyarDs.Tables("AYARLAR").Rows(0)("A1")
                    Database_Name = AyarDs.Tables("AYARLAR").Rows(0)("A2")
                    Depo_Kod = AyarDs.Tables("AYARLAR").Rows(0)("A3")
                    Servis_Url = AyarDs.Tables("AYARLAR").Rows(0)("A4")
                    Kasa_yolu = AyarDs.Tables("AYARLAR").Rows(0)("A5")
                    Terazi_Yolu = AyarDs.Tables("AYARLAR").Rows(0)("A6")
                    Yazici_Yolu = AyarDs.Tables("AYARLAR").Rows(0)("A7")
                    Etiket_Miktari = AyarDs.Tables("AYARLAR").Rows(0)("A8")
                    Kasa_Kod = AyarDs.Tables("AYARLAR").Rows(0)("A9")
                    Uzak_kasa_yol = AyarDs.Tables("AYARLAR").Rows(0)("A10")
                    SatisDosyaAdi = AyarDs.Tables("AYARLAR").Rows(0)("A11")
                    Kasa_Tipi = [Enum].Parse(GetType(KasaTipi), AyarDs.Tables("AYARLAR").Rows(0)("A12"))
                    Pasif_Stok_Aktarilsin = AyarDs.Tables("AYARLAR").Rows(0)("A13")
                    Opa_Yol = AyarDs.Tables("AYARLAR").Rows(0)("A14")
                    If AyarDs.Tables("AYARLAR").Columns.Contains("A15") = True Then
                        SatisDepoKod = AyarDs.Tables("AYARLAR").Rows(0)("A15")
                    End If

                    If AyarDs.Tables("AYARLAR").Columns.Contains("A16") = True Then
                        HalkDepoKod = AyarDs.Tables("AYARLAR").Rows(0)("A16")
                    End If

                    If AyarDs.Tables("AYARLAR").Columns.Contains("A17") = True Then
                        HalkGunu = AyarDs.Tables("AYARLAR").Rows(0)("A17")
                    End If

                    If AyarDs.Tables("AYARLAR").Columns.Contains("A18") = True Then
                        ProgramTipi = [Enum].Parse(GetType(ProgramTipleri), AyarDs.Tables("AYARLAR").Rows(0)("A18"))
                    End If

                    If AyarDs.Tables("AYARLAR").Columns.Contains("A19") = True Then
                        CalismaSekli = [Enum].Parse(GetType(CalismaTipi), AyarDs.Tables("AYARLAR").Rows(0)("A19"))
                    Else
                        CalismaSekli = CalismaTipi.Servis
                    End If

                    If AyarDs.Tables("AYARLAR").Columns.Contains("A20") = True Then
                        ImportsFile = AyarDs.Tables("AYARLAR").Rows(0)("A20")
                    End If

                    If AyarDs.Tables("AYARLAR").Columns.Contains("A21") = True Then
                        TeraziTipi = [Enum].Parse(GetType(TeraziTip), AyarDs.Tables("AYARLAR").Rows(0)("A21"))
                    End If

                    If AyarDs.Tables("AYARLAR").Columns.Contains("A22") = True Then
                        otoSendTime = AyarDs.Tables("AYARLAR").Rows(0)("A22")
                    End If

                    If AyarDs.Tables("AYARLAR").Columns.Contains("A23") = True Then
                        KdvSiralamasi = AyarDs.Tables("AYARLAR").Rows(0)("A23")
                    End If

                    If AyarDs.Tables("AYARLAR").Columns.Contains("A24") = True Then
                        fiyatGruplari = AyarDs.Tables("AYARLAR").Rows(0)("A24")
                    End If

                End If
            End If
        End If
    End Sub

    Public Sub CompactDB()
        Try
            Dim connectionString As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Persist Security Info=True;Jet OLEDB:Database Password=s1h2i3e4l5d6", Application.StartupPath & "\VT\MikroMagaza.mdb")
            Dim objJRO As Object = System.Activator.CreateInstance(System.Type.GetTypeFromProgID("JRO.JetEngine"))

            Dim oParams As Object() = New Object() {connectionString, String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5;Jet OLEDB:Database Password=s1h2i3e4l5d6", Application.StartupPath & "\VT\tmp.mdb")}
            objJRO.GetType().InvokeMember("CompactDatabase", System.Reflection.BindingFlags.InvokeMethod, Nothing, objJRO, oParams)

            File.Delete(String.Format(Application.StartupPath & "\VT\{0}{1}{2}.mdb", Now.Day, Now.Month, Now.Year))
            System.IO.File.Move(Application.StartupPath & "\VT\MikroMagaza.mdb", String.Format(Application.StartupPath & "\VT\{0}{1}{2}.mdb", Now.Day, Now.Month, Now.Year))
            System.IO.File.Move(Application.StartupPath & "\VT\tmp.mdb", Application.StartupPath & "\VT\MikroMagaza.mdb")

            System.Runtime.InteropServices.Marshal.ReleaseComObject(objJRO)
            objJRO = Nothing
        Catch ex As Exception

        End Try
    End Sub

    Public Sub ImportData()
        Dim Cnn_str1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\VT\import.mdb"
        Dim Cnn_str2 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\VT\MikroMagaza.mdb"

        If File.Exists(Application.StartupPath & "\VT\import.MDB") = True Then
            Dim cn_kaynak As New OleDb.OleDbConnection(Cnn_str1) 'import db
            cn_kaynak.Open()
            Dim cn_hedef As New OleDb.OleDbConnection(Cnn_str2) 'smart office
            cn_hedef.Open()

            Dim trn As OleDb.OleDbTransaction
            trn = cn_hedef.BeginTransaction


            Dim cmd_delete As New OleDb.OleDbCommand
            cmd_delete.Connection = cn_hedef
            cmd_delete.Transaction = trn
            cmd_delete.CommandText = "DELETE FROM TBL_STOK"
            cmd_delete.ExecuteNonQuery()
            cmd_delete.CommandText = "DELETE FROM TBL_BARKOD"
            cmd_delete.ExecuteNonQuery()
            cmd_delete.CommandText = "DELETE FROM TBL_STOKDEPO"
            cmd_delete.ExecuteNonQuery()
            'trn.Commit()



            'bu kısım import database den verileri smart office db ye alıyor
            Dim cmd_read As New OleDb.OleDbCommand
            cmd_read.Connection = cn_kaynak
            cmd_read.CommandText = "SELECT * FROM TBL_STOK"
            Dim rd As OleDb.OleDbDataReader
            rd = cmd_read.ExecuteReader

            Dim cmd_ins As New OleDb.OleDbCommand
            cmd_ins = Generate_insert(rd.GetSchemaTable, "TBL_STOK")
            cmd_ins.Connection = cn_hedef
            cmd_ins.Transaction = trn

            While rd.Read
                For i As Integer = 0 To rd.FieldCount - 1
                    cmd_ins.Parameters(i).Value = rd(i)
                Next
                cmd_ins.ExecuteNonQuery()
            End While
            rd.Close()

            cmd_read.CommandText = "SELECT * FROM TBL_BARKOD"
            rd = cmd_read.ExecuteReader
            Dim cmd_ins2 As New OleDb.OleDbCommand
            cmd_ins2 = Generate_insert(rd.GetSchemaTable, "TBL_BARKOD")
            cmd_ins2.Connection = cn_hedef
            cmd_ins2.Transaction = trn

            While rd.Read
                For i As Integer = 0 To rd.FieldCount - 1
                    cmd_ins2.Parameters(i).Value = rd(i)
                Next
                cmd_ins2.ExecuteNonQuery()
            End While
            rd.Close()



            cmd_read.CommandText = "SELECT * FROM TBL_STOKDEPO"
            rd = cmd_read.ExecuteReader
            Dim cmd_ins3 As New OleDb.OleDbCommand
            cmd_ins3 = Generate_insert(rd.GetSchemaTable, "TBL_STOKDEPO")
            cmd_ins3.Connection = cn_hedef
            cmd_ins3.Transaction = trn

            While rd.Read
                For i As Integer = 0 To rd.FieldCount - 1
                    cmd_ins3.Parameters(i).Value = rd(i)
                Next
                cmd_ins3.ExecuteNonQuery()
            End While
            rd.Close()

            trn.Commit()
            cn_hedef.Close()
            cn_kaynak.Close()
        End If
    End Sub


    Private Function Generate_insert(ByVal dt As DataTable, ByVal tablo_ad As String) As OleDb.OleDbCommand
        Dim kolon As String = ""
        Dim tip As System.Type
        Dim c_kolon As String = ""
        Dim c_tip As OleDb.OleDbType
        Dim cmd As New OleDb.OleDbCommand

        Dim ins_txt As String = "INSERT INTO " & tablo_ad & " ("
        Dim line As String = ""

        For i As Integer = 0 To dt.Rows.Count - 1
            kolon = dt.Rows(i)("ColumnName")
            tip = dt.Rows(i)("DataType")
            c_kolon = "@" & kolon
            c_tip = DataType2(tip.ToString)

            line &= kolon

            If i < dt.Rows.Count - 1 Then
                line &= ","
            Else
                line &= ")"
            End If
        Next

        Dim line2 As String = ""
        For i As Integer = 0 To dt.Rows.Count - 1
            kolon = dt.Rows(i)("ColumnName")
            tip = dt.Rows(i)("DataType")
            c_kolon = "@" & kolon
            c_tip = DataType2(tip.ToString)
            line2 &= c_kolon
            If i < dt.Rows.Count - 1 Then
                line2 &= ","
            Else
                line2 &= ")"
            End If
        Next

        cmd.CommandText = ins_txt & line & " VALUES (" & line2
        For i As Integer = 0 To dt.Rows.Count - 1
            kolon = dt.Rows(i)("ColumnName")
            tip = dt.Rows(i)("DataType")
            c_kolon = "@" & kolon
            c_tip = DataType2(tip.ToString)
            cmd.Parameters.Add(c_kolon, c_tip)
        Next

        Return cmd
    End Function


    Private Function DataType2(ByVal ad As String) As OleDb.OleDbType
        Select Case ad
            Case "int"
                Return OleDb.OleDbType.Integer
            Case "smallint"
                Return OleDb.OleDbType.Integer
            Case "bit"
                Return OleDb.OleDbType.Boolean
            Case "varchar"
                Return OleDb.OleDbType.VarChar
            Case "datetime"
                Return OleDb.OleDbType.Date
            Case "binary"
                Return OleDb.OleDbType.Integer
            Case "float"
                Return OleDb.OleDbType.Decimal
            Case "tinyint"
                Return OleDb.OleDbType.Integer
            Case "decimal"
                Return OleDb.OleDbType.Decimal
            Case Else
                Return OleDb.OleDbType.VarChar
        End Select
    End Function

    Private Sub DovizYukle()
        Dim cn As New OleDbConnection(Cnn_String)
        cn.Open()
        Dim cmd As New OleDbCommand
        cmd.Connection = cn
        cmd.CommandText = "SELECT * FROM TBL_DOVIZKURLARI"
        Dim rd As OleDbDataReader = cmd.ExecuteReader()
        DovizListe.Add(0, 1) 'TL
        While rd.Read
            DovizListe.Add(rd(0), rd(1)) 'TL
        End While
        rd.Close()
        cn.Close()
    End Sub

    Public Function DovizKuru(ByVal DovizCinsi As Integer, ByVal Fiyat As Decimal) As Decimal
        If DovizListe.Count > 0 Then
            If DovizListe.ContainsKey(DovizCinsi) Then
                Return DovizListe(DovizCinsi) * Fiyat
            Else
                Return Fiyat
            End If
        Else
            DovizYukle()
            If DovizListe.Count > 0 Then
                If DovizListe.ContainsKey(DovizCinsi) Then
                    Return DovizListe(DovizCinsi) * Fiyat
                Else
                    Return Fiyat
                End If
            Else
                Return Fiyat
            End If
        End If
    End Function


    Public Function CreateChecksum(ByVal EAN As String) As String
        Dim csumTotal As Integer = 0 ' The checksum working variable starts at zero
        ' Calculate the checksum value for the message
        Dim charPos As Integer
        For charPos = EAN.Length - 1 To 0 Step -1
            If charPos Mod 2 = 0 Then
                csumTotal = csumTotal + Integer.Parse(EAN.Substring(charPos, 1))
            Else
                csumTotal = csumTotal + 3 * Integer.Parse(EAN.Substring(charPos, 1))
            End If
        Next charPos
        ' Calculate the checksum digit
        Dim remainder As Integer = 10 - csumTotal Mod 10
        remainder = remainder Mod 10
        Return EAN & remainder.ToString()
    End Function 'CreateChecksum

End Module
